package com.nsgf.library;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.netease.yunxin.kit.conversationkit.local.ui.fun.page.FunLocalConversationFragment;
import com.netease.yunxin.kit.conversationkit.ui.fun.page.FunConversationFragment;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.UserDataBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.BaseFragment;
import com.nsgf.library.ui.page.LoginActivity;
import com.nsgf.library.ui.page.ShoppingCartActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.ui.page.home.HomeFragment;
import com.nsgf.library.ui.page.home.ManagerFragment;
import com.nsgf.library.ui.page.home.MineFragment;
import com.nsgf.library.ui.page.home.ShoppingCartFragment;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.view.MyRadioButton;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.ActivityNsgfMainBinding;
import com.zhht.htzx.ui.GoodsBusinessListActivity;
import com.zhht.htzx.ui.LoginTypeActivity;
import com.zhht.htzx.ui.OrderBusinessListActivity;
import com.zhht.htzx.ui.QRCodeScannerActivity;
import com.zhht.htzx.ui.UserRecordActivity;
import com.zhht.htzx.ui.VirtualCurrencyActivity;
import com.zhht.htzx.ui.WithdrawalActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.TimerTask;

public class MainNsgfActivity extends BaseActivity {

    private LoginStates mStates;

    List<MyRadioButton> menuList;

    private AccountRequester mAccountRequester;
    private Fragment pages[];
    private int lastIndexOfPage = 0;
    private long exitTime = 0L;
    private boolean isEventBusRegistered = false;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(LoginStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);

    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_nsgf_main, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }

    private IWXAPI api;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityNsgfMainBinding) getBinding();

        api = WXAPIFactory.createWXAPI(this, APIs.APP_ID, false);


        api.registerApp(APIs.APP_ID);
        getLifecycle().addObserver(mAccountRequester);
        if (1 == UserInfo.getInstance().getIsMerchant()) {
            mBinding.rlBusiness.setVisibility(VISIBLE);
            mBinding.rlUser.setVisibility(GONE);
            mStates.titleBar.set("工作台");
            mAccountRequester.getBusinessDetail();
            mAccountRequester.getUserDataResult().observe(this, new Observer<ResponseStatus<UserDataBean>>() {
                @Override
                public void onChanged(ResponseStatus<UserDataBean> responseStatus) {
                    if (responseStatus.getResponseCode() == 0) {
                        mStates.businessData.set(responseStatus.getData());
                    }
                }
            });
        } else {

            mBinding.rlBusiness.setVisibility(GONE);
            mBinding.rlUser.setVisibility(VISIBLE);
            if (null == menuList) {
                menuList = new ArrayList<>();
                menuList.add(mBinding.rbHome);
                menuList.add(mBinding.rbPersonCenter);
                menuList.add(mBinding.rbTest);
                menuList.add(mBinding.rbShoppingCart);
                menuList.add(mBinding.rbManager);
            }
//            pages = new BaseFragment[]{new HomeFragment(), ManagerFragment.newInstance(0), ManagerFragment.newInstance(1), new ShoppingCartFragment(), new MineFragment()};

            pages = new Fragment[]{new HomeFragment(), ManagerFragment.newInstance(1), new FunLocalConversationFragment(), ManagerFragment.newInstance(3), new MineFragment()};
            displayPage(0);

            if (!isEventBusRegistered) {
                EventBus.getDefault().register(this);
                isEventBusRegistered = true;
            }
            String[] permission;


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                permission = new String[]{Manifest.permission.POST_NOTIFICATIONS,
                        Manifest.permission.ACCESS_FINE_LOCATION};
            } else {
                permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (1 == UserInfo.getInstance().getIsMerchant()) {
            mBinding.rlBusiness.setVisibility(VISIBLE);
            mBinding.rlUser.setVisibility(GONE);
            mStates.titleBar.set("工作台");
            mAccountRequester.getBusinessDetail();
            mAccountRequester.getUserDataResult().observe(this, new Observer<ResponseStatus<UserDataBean>>() {
                @Override
                public void onChanged(ResponseStatus<UserDataBean> responseStatus) {
                    if (responseStatus.getResponseCode() == 0) {
                        mStates.businessData.set(responseStatus.getData());
                        UserInfo.getInstance().setAdminFlag(responseStatus.getData().isAdminFlag());
                        UserInfo.getInstance().setIsMerchant(1);
                        if (responseStatus.getData().isAdminFlag()) {
                            mBinding.llAdmin.setVisibility(VISIBLE);
                        } else {
                            mBinding.llAdmin.setVisibility(GONE);
                        }
                    }
                }
            });
        } else {
            mBinding.rlBusiness.setVisibility(GONE);
            mBinding.rlUser.setVisibility(VISIBLE);
            if (null == menuList) {
                menuList = new ArrayList<>();
                menuList.add(mBinding.rbHome);
                menuList.add(mBinding.rbPersonCenter);
                menuList.add(mBinding.rbTest);
                menuList.add(mBinding.rbShoppingCart);
                menuList.add(mBinding.rbManager);
                pages = new BaseFragment[]{new HomeFragment(), ManagerFragment.newInstance(1), ManagerFragment.newInstance(2), ManagerFragment.newInstance(3), new MineFragment()};
                displayPage(0);

                String[] permission;


                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    permission = new String[]{Manifest.permission.POST_NOTIFICATIONS,
                            Manifest.permission.ACCESS_FINE_LOCATION};
                } else {
                    permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
                }
            }
        }
    }

    public static class LoginStates extends StateHolder {

        public final State<UserDataBean> businessData = new State<>(new UserDataBean());

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isEventBusRegistered) {
            try {
                EventBus.getDefault().unregister(this);
                isEventBusRegistered = false;
            } catch (Exception e) {
                // 忽略注销异常
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventMsg event) {
        if ("2".equals(event.getMsg())) {
            modflyMenuStyle(mBinding.rbManager);
            displayPage(2);
        }
    }


    private MyRadioButton lastChecked;

    private ActivityNsgfMainBinding mBinding;

    public class ClickProxy {

        public void BottomClickHome() {
            modflyMenuStyle(mBinding.rbHome);
            displayPage(0);
        }

        public void BottomClickTest() {
            modflyMenuStyle(mBinding.rbTest);
            displayPage(1);
        }

        public void BottomClickManager() {
            modflyMenuStyle(mBinding.rbManager);
            displayPage(2);
        }

        public void BottomClickCart() {
            modflyMenuStyle(mBinding.rbShoppingCart);
            displayPage(3);
        }

        public void BottomClickMine() {
            modflyMenuStyle(mBinding.rbPersonCenter);
            displayPage(4);
        }


        public void openLoginType() {
            UserInfo.getInstance().clearUserInfo();
            onResume();
            startActivity(new Intent().setClass(MainNsgfActivity.this, LoginTypeActivity.class));
        }

        public void scanQRCode() {
            Intent intent = new Intent(MainNsgfActivity.this, QRCodeScannerActivity.class);
            startActivity(intent);
        }

        public void openOrder() {
            startActivity(new Intent(MainNsgfActivity.this, OrderBusinessListActivity.class));
        }

        public void openGoods() {
            startActivity(new Intent(MainNsgfActivity.this, GoodsBusinessListActivity.class));
        }

        public void openUser() {
            startActivity(new Intent(MainNsgfActivity.this, UserRecordActivity.class)
                    .putExtra("amountWithdrawal", mStates.businessData.get().getAmountWithdrawal()));
        }

        public void openWithdrawal() {
            startActivity(new Intent(MainNsgfActivity.this, WithdrawalActivity.class)
                    .putExtra("amountWithdrawal", mStates.businessData.get().getAmountWithdrawal()));
        }

        public void openVirtualCurrency(int type) {
            startActivity(new Intent(MainNsgfActivity.this, VirtualCurrencyActivity.class)
                    .putExtra("type", type)
                    .putExtra("data", mStates.businessData.get()));
        }

        /**
         * 悬浮按钮点击事件
         */
        public void onFloatingButtonClick() {
            // 添加点击动画效果
            android.view.animation.Animation scaleIn = android.view.animation.AnimationUtils.loadAnimation(MainNsgfActivity.this, R.anim.fab_scale_in);
            android.view.animation.Animation scaleOut = android.view.animation.AnimationUtils.loadAnimation(MainNsgfActivity.this, R.anim.fab_scale_out);

            mBinding.fabFloating.startAnimation(scaleIn);
            scaleIn.setAnimationListener(new android.view.animation.Animation.AnimationListener() {
                @Override
                public void onAnimationStart(android.view.animation.Animation animation) {
                }

                @Override
                public void onAnimationEnd(android.view.animation.Animation animation) {
                    mBinding.fabFloating.startAnimation(scaleOut);
                }

                @Override
                public void onAnimationRepeat(android.view.animation.Animation animation) {
                }
            });

            // 这里可以添加悬浮按钮的具体功能
            // 例如：显示一个对话框、跳转到特定页面等

            if (!StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
                startActivity(new Intent().setClass(MainNsgfActivity.this, ShoppingCartActivity.class));
            } else {
                startActivity(new Intent().setClass(MainNsgfActivity.this, LoginActivity.class));
            }
        }


    }


    /**
     * 修改menu样式
     *
     * @param rb
     */
    private void modflyMenuStyle(MyRadioButton rb) {
        rb.setChecked(true);
        for (MyRadioButton menuBtn : menuList) {
            if (menuBtn != rb) {
                menuBtn.setChecked(false);
            }
        }
        lastChecked = rb;
    }


    /**
     * @param index
     */
    public void displayPage(int index) {
        Fragment bf = pages[index];
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (bf.isAdded())
            ft.show(bf);
        else
            ft.add(R.id.content_container, bf);
        if (lastIndexOfPage < pages.length && lastIndexOfPage >= 0 && lastIndexOfPage != index)
            ft.hide(pages[lastIndexOfPage]);
        ft.commit();
        lastIndexOfPage = index;
    }

    /**
     * 内存重启后防止fragment出现重叠现象
     */
    private void whenMemoryReload() {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        for (Fragment f : fragments) {
            ft.hide(f);
        }
        ft.commitAllowingStateLoss();
    }

    MessageReceiver mMessageReceiver;

    public void registerMessageReceiver() {

        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION_BOTTOM);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION_BOTTOM.equals(intent.getAction())) {
                    modflyMenuStyle(mBinding.rbManager);
                    displayPage(2);
                }
            } catch (Exception e) {
            }
        }

    }

    /**
     * 监听返回次数，出应用
     */
    int clickTimes = 0;// 点击返回键次数

    @Override
    public void onBackPressed() {
        //不关闭页面，跳转到桌面
        super.onBackPressed();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            clickTimes++;
            java.util.Timer timer = new java.util.Timer(true);

            TimerTask task = new TimerTask() {
                public void run() {
                    clickTimes = 0;
                }
            };
            timer.schedule(task, 1600);

            if (clickTimes <= 1) {
                ToastUtils.showLongToast("再按一次退出应用");
            } else {
                finish();
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

}
